<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-01-30
 * Time: 10:02:04
 * Info: 角色组控制器
 */
defined('IN_YZMPHP') or exit('Access Denied');
yzm_base::load_controller('common', 'admin', 0);

class authgroup extends common
{

    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = D('auth_group');
    }

    public function init()
    {
        if (is_ajax()) {
            $limit = (int)input('limit', 10);
            $page  = (int)input('page', 1);
            $first = ($page - 1) * $limit;
            $field = input('field', 'id');
            $order = input('order', 'asc');
            $key   = input('key');
            $list  = $this->model->limit("{$first},{$limit}")->order("{$field} {$order}")->select();
            foreach ($list as $key => $v) {
                $list[$key]['createtime'] = date("Y-m-d H:i:s", $list[$key]['createtime']);
            }
            $count = $this->model->total();
            return_json(['code' => 0, 'msg' => 'ok', 'data' => $list, 'count' => $count]);
        }
        include $this->admin_tpl('auth_group/index');
    }

    public function add()
    {
        if (is_post()) {
            $param = input('post.');
            if (empty($param['name'])) {
                return_error("角色名称不能为空");
            }
            $param['name']        = remove_xss($param['name']);
            $param['rules']       = remove_xss($param['rules']);
            $param['status']      = $param['status'] == 1 ? 'normal' : 0;
            $param['create_time'] = time();
            $param['update_time'] = time();
            $this->model->insert($param, ['id' => $param['id']]);
            return_success("保存成功");
        }
        include $this->admin_tpl('auth_group/add');
    }

    public function edit()
    {
        if (is_post()) {
            $param = input('post.');

            if (empty($param['id'])) {
                return_error("参数错误");
            }
            if (empty($param['name'])) {
                return_error("角色名称不能为空");
            }
            $param['id']    = (int)$param['id'];
            $param['name']  = remove_xss($param['name']);
            $param['rules'] = remove_xss($param['rules']);

            if ($param['id'] == 1) {
                return_error("不允许修改id为1的哦");
            }
            $param['status']      = $param['status'] == 1 ? 'normal' : 0;
            $param['update_time'] = time();
            $this->model->update($param, ['id' => $param['id']]);
            return_success("保存成功");
        }
        $id = (int)input('get.id');
        if (empty($id)) {
            showmsg('参数错误','stop');
        }
        if ($id == 1) {
            showmsg('不允许修改id为1的哦','stop');
        }
        $data = $this->model->where(['id' => $id])->find();
        include $this->admin_tpl('auth_group/edit');
    }

    public function delete()
    {
        if (is_post()) {
            $id = (int)input('get.id');
            if (empty($id)) {
                return_error("参数错误");
            }
            if ($id == 1) {
                return_error("不允许删除id为1的哦");
            }
            $this->model->delete(['id' => $id]);
            return_success("删除成功");
        }
    }

    //权限节点
    public function authorize()
    {
        if (is_ajax()) {
            $id  = input('get.id');
            $row = $this->model->where(['id' => $id])->find();
            if (empty($row)) {
                return_error('数据不存在');
            }
            $list = $this->getAuthorizeNodeListByAdminId($row['rules']);

            return_success("ok", $list);
        }
    }

    /**
     * 根据角色ID获取授权节点
     *
     * @param $authId
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAuthorizeNodeListByAdminId($checkNodeList)
    {
        $pk    = "id";
        $pid   = "pid";
        $root  = 0;
        $child = "children";

        $list         = D('auth_rule')->where(['is_auth' => 1])->field('id,node,title,type,is_auth,pid')->order('id asc,node asc')->select();
        $checkNodeArr = [];
        if ($checkNodeList != '*') {
            $checkNodeArr = explode(",", $checkNodeList);
        }
        foreach ($list as $key => $v) {
            $list[$key]['field']   = 'node';
            $list[$key]['spread']  = true;
            $list[$key]['checked'] = in_array($v['id'], $checkNodeArr) ? true : false;
        }
        $newNodeList = [];

        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                $list[$key]['title'] = "{$data['title']}【{$data['node']}】";
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $newNodeList[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent           =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }

        }

        return $newNodeList;
    }

}
